package cn.maxhou.util.fastjson2;


import com.alibaba.fastjson2.util.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.util.Date;

public class String2DateConverter implements Converter<String, Date> {
    //支持转换的日期格式(有默认值,也可以注入)
    private String[] dateFormats={
        "yyyy-MM-dd","yyyy-MM-dd HH:mm:ss","yyyy/MM/dd"
    };
    public void setDateFormats(String[] dateFormats) {
        this.dateFormats = dateFormats;
    }
    @Override
    public Date convert(String source) {
        for (int i = 0; i < dateFormats.length; i++) {
            try{
                //尝试没一个格式进行转换
                return DateUtils.parseDate(source, dateFormats[i]);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        throw  new RuntimeException("日期格式转换失败,值为: "+source);
    }
}
